import json
import requests

from pyoauth2 import Client

KEY = '0dee05268696891d29ca0f7393c39b57'
SECRET = '7aa957dd9b5b663a'
CALLBACK = 'http://xgz.xkk.pw/social/bind/douban'
USERINFO_URL = 'https://api.douban.com/v2/user/~me'


client = Client(KEY, SECRET,
                site='https://api.douban.com',
                authorize_url='https://www.douban.com/service/auth2/auth',
                token_url='https://www.douban.com/service/auth2/token')


authorize_url = client.auth_code.authorize_url(redirect_uri=CALLBACK,
                                               scope='shuo_basic_w,shuo_basic_r,douban_basic_common')


def get_token_response(code_str):
    code_str = code_str.strip()
    payload = {'client_id': KEY, 'client_secret': SECRET,
               'redirect_uri': CALLBACK, 'grant_type': 'authorization_code',
               'code': code_str}
    response = requests.post(client.token_url(), data=payload)
    response = json.loads(response.text)
    return response


def get_user_info(token):
    headers = {'Authorization': 'Bearer '+token}
    response = requests.get(USERINFO_URL, headers=headers)
    return response.text
